package com.molyfun.core.resolvers;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.io.IOUtils;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.alibaba.fastjson.JSON;
import com.molyfun.core.annotation.CurrentUserBean;
import com.molyfun.core.util.CommonUtil;
import com.molyfun.model.student.HoUserBean;

/**
 * 增加方法注入，将含有CurrentUser注解的方法参数注入当前登录用户
 * @author shidongsheng
 */
public class CurrentUserBeanMethodArgumentResolver implements HandlerMethodArgumentResolver {


	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.hasParameterAnnotation(CurrentUserBean.class);
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		String body = getRequestBody(webRequest);
		String arg = parameter.getParameterAnnotation(CurrentUserBean.class).value();
		if (StringUtils.isEmpty(arg)) {
			arg = parameter.getParameterName();
		}
		Object val = JSON.parseObject(body, HoUserBean.class);
		CommonUtil.checkBeanImgpath(val);
		return val;
	}

	private String getRequestBody(NativeWebRequest webRequest){
		String body = null;
		try{
			HttpServletRequest servletRequest = webRequest.getNativeRequest(HttpServletRequest.class);

			body = IOUtils.toString(servletRequest.getInputStream());
		} catch (IOException e) {
			throw new RuntimeException(e);
		}
		return body;
	}
}
